package com.omkarpatil.learningjpa2.mapping.onetoone.sharedpk;

import javax.persistence.EntityManager;

import com.omkarpatil.learningjpa2.util.EntityManagerFactoryFactory;

public class TestDriver {

	public static void main(String[] args) {
		EntityManager em1 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em1.getTransaction().begin();

		System.out.println("##### Adding User to database ...");
		User user = new User("Omkar Patil");

		System.out.println("##### Adding Profile to database ...");
		Profile profile = new Profile("abc@cde.com");
		profile.setUser(user);
		
		user.setProfile(profile);
		
		em1.persist(user);
		em1.persist(profile);
		
		em1.getTransaction().commit();
		em1.close();
		
		int userId = user.getId();
		System.out.printf("##### User Id of Omkar Patil : %s \n", userId);
		
		EntityManager em2 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em2.getTransaction().begin();
		System.out.printf("##### Fetching User using userId = %s\n", userId);
		
		User user2 = em2.find(User.class, userId);
		System.out.printf("User Name: %s, Email: %s", user2.getName(), user.getProfile().getEmail());
		
/*		Profile profile2 = em2.createNamedQuery("getProfileForUser", Profile.class)
			.setParameter("userId", userId).getSingleResult();
		
		System.out.printf("##### User : %s, Email : %s", profile2.getUser().getName(), profile2.getEmail());*/
		
		em2.getTransaction().commit();
		em2.close();
	}

}
